<?php

class ProductsAction extends fvAction {

	function __construct () {
		parent::__construct(fvSite::$Layoult);
	}

	function executeIndex() {
		if (fvRequest::getInstance()->isXmlHttpRequest())
		return self::$FV_NO_LAYOULT;
		else return self::$FV_OK;
	}

	function executeEdit() {
		if (fvRequest::getInstance()->isXmlHttpRequest())
		return self::$FV_AJAX_CALL;
		else return self::$FV_OK;
	}

	function executeSave() {
		$request = fvRequest::getInstance();
		if (!$Products = ProductsManager::getInstance()->getByPk($request->getRequestParameter('id'))) {
			$Products = new Products();
		}
		$n = $request->getRequestParameter('n');
		$upload = $request->getRequestParameter('upload');
		if (is_array($upload["main_photo"])){
			$n["main_photo"] = $upload["main_photo"];
		}
		if (is_array($n["photo"]) && is_array($upload["photo"]))
			$n["photo"] = array_merge($n["photo"], $upload["photo"]);
		elseif (is_array($upload["photo"])){
			$n["photo"] = $upload["photo"];
		}
		$loggedUser = fvSite::$fvSession->getUser();
    	if ($loggedUser->is_root || $loggedUser->group_id == 1){
    		
    	}
    	else{
    		$n["user_id"] = $loggedUser->getPk();
    	}
		$Products->updateFromRequest($n);
		if ($Products->save()) {
			fvResponce::getInstance()->setHeader('Id', $Products->getPk());
			if (isset($upload["photo"])){
	        	foreach ($upload["photo"] as $photo){
	        		if (file_exists(fvSite::$fvConfig->get('path.upload.tmp_dir') . $photo['file']) && is_file(fvSite::$fvConfig->get('path.upload.tmp_dir') . $photo['file'])){
	        			$Products->saveUploadFile('photo', fvSite::$fvConfig->get('path.upload.tmp_dir') . $photo['file'], $photo['file']);
	        		}
	        	}
        	}
			if (isset($upload["main_photo"])){
        		if (file_exists(fvSite::$fvConfig->get('path.upload.tmp_dir') . $upload["main_photo"]['file']) && is_file(fvSite::$fvConfig->get('path.upload.tmp_dir') . $upload["main_photo"]['file'])){
        			$Products->saveUploadFile('main_photo', fvSite::$fvConfig->get('path.upload.tmp_dir') . $upload["main_photo"]['file'], $upload["main_photo"]['file']);
        		}
        	}
        	$filter = $request->getRequestParameter('filter');
        	$set_filters = $request->getRequestParameter('set_filters');
        	if (is_array($filter)){
        		$query = "delete from krshop_product_filters where product_id=?";
        		$res = fvSite::$DB->query($query, array($Products->getPk()));
        		if (!$set_filters)
        		foreach ($filter as $k=>$f){
        			$query = "insert into krshop_product_filters values (?, ?, ?)";
        			$res = fvSite::$DB->query($query, array($Products->getPk(), $k, $f));
        		}
        	}
			$this->setFlash("Данные успешно сохранены", self::$FLASH_SUCCESS);
			if ($request->getRequestParameter('redirect')) {
				fvResponce::getInstance()->setHeader('redirect', fvSite::$fvConfig->get('dir_web_root') . $request->getRequestParameter('module') . "/");
			}
			else{
				fvResponce::getInstance()->setHeader('redirect', fvSite::$fvConfig->get('dir_web_root') . $request->getRequestParameter('module') . "/edit/?id=".$Products->getPk()."&_rand=".rand());
			}
		} else {
			fvResponce::getInstance()->setHeader('X-JSON', json_encode($Products->getValidationResult()));
			$string = '';
			foreach ($Products->getValidationResult() as $error){
				$string .= $error."!<br>";
			}
			$this->setFlash("Ошибка при сохранении данных проверьте правильность введенных данных!<br>".$string, self::$FLASH_ERROR);
		}

		if (fvRequest::getInstance()->isXmlHttpRequest())
		return self::$FV_AJAX_CALL;
		else return self::$FV_OK;
	}
	
	function executeDelete() {
		$request = fvRequest::getInstance();
		if (!$Products = ProductsManager::getInstance()->getByPk($request->getRequestParameter('id'))) {
			$this->setFlash("Ошибка при удалении.", self::$FLASH_ERROR);
		} else {
			$Products->delete();
			$this->setFlash("Данные успешно удалены", self::$FLASH_SUCCESS);
		}

		fvResponce::getInstance()->setHeader('redirect', fvSite::$fvConfig->get('dir_web_root') . $request->getRequestParameter('module') . "/");
		if (fvRequest::getInstance()->isXmlHttpRequest())
		return self::$FV_NO_LAYOULT;
		else return self::$FV_OK;
	}
	
	function executeDeleteimage() {
		$request = fvRequest::getInstance();
		if (!$Products = ProductsManager::getInstance()->getByPk($request->getRequestParameter('id'))) {
			$this->setFlash("Ошибка при удалении.", self::$FLASH_ERROR);
		} else {
			if ($Products->main_photo){
				if ($Products->main_photo["file"] == $request->getRequestParameter('photo')){
					$Products->main_photo = array();
					$Products->save(false);
				}
			}
			if ($Products->photo){
				$tmp = $Products->photo;
				foreach ($tmp as $k=>$photo){
					if ($photo["file"] == $request->getRequestParameter('photo')){
						unset($tmp[$k]);
					}
				}
				$Products->photo = $tmp;
				$Products->save(false); 
			}
			$this->setFlash("Фотография успешно удалена", self::$FLASH_SUCCESS);
		}

		fvResponce::getInstance()->setHeader('redirect', fvSite::$fvConfig->get('dir_web_root') . $request->getRequestParameter('module') . "/edit/?id={$request->getRequestParameter('id')}");
		if (fvRequest::getInstance()->isXmlHttpRequest())
		return self::$FV_NO_LAYOULT;
		else return self::$FV_OK;
	}
	
	function executeUploadimage () {
        return self::$FV_AJAX_CALL;
    }

}

?>
